﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;

namespace MSL.Utility.Doc
{
    /// <summary>
    /// json数据操作类
    /// </summary>
    public class Json
    {
        #region 构造/析构函数

        public Json()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        ~Json()
        {
            Dispose();
        }
        #endregion

        #region JSON转对象

        /// <summary>
        /// 将json转换为data
        /// </summary>
        /// <param name="json">得到的json</param>
        /// <returns></returns>
        public DataTable JsonToData(string json)
        {
            //转换json格式
            json = json.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
            //取出表名   
            var rg = new System.Text.RegularExpressions.Regex(@"(?<={)[^:]+(?=:\[)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            string strName = rg.Match(json).Value;
            DataTable tb = null;
            //去除表名   
            json = json.Substring(json.IndexOf("[") + 1);
            json = json.Substring(0, json.IndexOf("]"));

            //获取数据   
            rg = new System.Text.RegularExpressions.Regex(@"(?<={)[^}]+(?=})");
            System.Text.RegularExpressions.MatchCollection mc = rg.Matches(json);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split('*');
                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split('#');

                        if (strCell[0].Substring(0, 1) == "\"")
                        {
                            int a = strCell[0].Length;
                            dc.ColumnName = strCell[0].Substring(1, a - 2);
                        }
                        else
                        {
                            dc.ColumnName = strCell[0];
                        }
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }
                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split('#')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;
        }
        #endregion

        #region 对象转JSON

        /// <summary>
        /// <summary> data转json</summary>
        /// <param name="dt">数据库查询结果</param>
        /// <param name="fields">需要添加进来的字段名</param>
        /// 格式如下
        /// count : 6,
        /// root : [  {'id' : 1, 'name' : 'lislie' }, { 'id' : 2, 'name' : 'Mark' }... ]
        /// <returns></returns>
        public string DataToJson(DataTable dt, string[] fields)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"count\":" + dt.Rows.Count + ",\"root\":[");
            //sb.Append("{[");
            string json = "";
            if (dt == null || dt.Rows.Count == 0)
            {
                return "";
            }

            if (dt.Rows.Count > 0)
            {
                StringBuilder sbTemp = new StringBuilder();
                foreach (DataRow row in dt.Rows)
                {
                    sbTemp.Clear();
                    json = "{";
                    if (fields == null || fields.Length == 0)
                    {
                        foreach (DataColumn dc in dt.Columns)
                        {
                            sbTemp.Append("\"" + dc.ColumnName + "':'" + row[dc.ColumnName] + "\",");
                        }
                    }
                    else
                    {
                        foreach (string item in fields)
                        {
                            sbTemp.Append("'\"" + item + "':\"" + row[item] + "\",");
                        }
                    }
                    json = sbTemp.ToString();
                    json = json.Substring(0, json.Length - 1);
                    json += "},";
                    sb.Append(json);
                }
                json = sb.ToString();
                json = json.Substring(0, json.Length - 1);
                json += "]}";
            }
            else
            {
                json = sb.ToString();
                json += "]}";
            }

            return json;
        }

        #endregion

        #region 数据表转键值对集合
        /// <summary>
        /// data转成 List
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <returns>哈希表数组</returns>
        public List<Dictionary<string, object>> DataToList(DataTable dt)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    dic.Add(dc.ColumnName, dr[dc.ColumnName]);
                }
                list.Add(dic);
            }
            return list;
        }

        /// <summary>
        /// 数据集转键值对数组字典
        /// </summary>
        /// <param name="dataSet">数据集</param>
        /// <returns>键值对数组字典</returns>
        public Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
        {
            Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();
            foreach (DataTable dt in ds.Tables)
            {
                result.Add(dt.TableName, DataToList(dt));
            }
            return result;
        }
        #endregion

        #region 在数组里添加key,value
        /// <summary>
        /// 在集合中添加项
        /// </summary>
        /// <param name="list">集合</param>
        /// <param name="name">名</param>
        /// <param name="value">值</param>
        public void AddItem(ref List<string> list, string name, string value)
        {
            if (list == null)
            {
                list = new List<string>();
            }
            list.Add("\"" + name + "\":" + "\"" + value + "\"");
        }
        #endregion

        #region 将JSON文本转换为数据表数据
        /// <summary>
        /// 将JSON文本转换为数据表数据
        /// </summary>
        /// <param name="jsonText">JSON文本</param>
        /// <returns>数据表字典</returns>
        public List<Dictionary<string, object>> JsonToDictionary(string jsonText)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            DataTable dt = null;
            try
            {
                dt = JsonToData(jsonText);
                Dictionary<string, object> dic = null;
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        dic = new Dictionary<string, object>();
                        foreach (DataColumn dc in dt.Columns)
                        {
                            dic.Add(dc.ColumnName, dr[dc.ColumnName]);
                        }
                        list.Add(dic);
                    }
                }
            }
            catch (Exception)
            {

            }
            //return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);
            return list;
        }
        #endregion

        #region IDisposable 成员

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
